package org.game.module.event.handler;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.cfg.EventConditionCfg;
import org.cfg.TaskCfg;
import org.cfg.cache.EventConditionCfgCache;
import org.cfg.cache.TaskCfgCache;
import org.constant.EventConditionKey;
import org.game.db.bean.Player;
import org.game.db.bean.Task;
import org.game.manager.TaskManager;
import org.game.msgBuilder.TaskMsgBuilder;
import org.game.plugin.event.GameEvent;
import org.game.plugin.event.GameEventHandler;
import org.game.plugin.event.GameEventListener;
import org.game.plugin.event.GameEventStack;
import org.game.protobuf.s2c.S2CShareMsg.ChangeType;
import org.game.protobuf.s2c.S2CTaskMsg.TaskInfo;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
/**
 * 任务激活事件处理器
 * @author win7
 *
 */
public class TaskAcceptEventHandler implements GameEventHandler {


	/**
	 * 任务激活流程：
	 * 1.获取所有开放任务
	 * 2.筛选出未接任务
	 * 3.检查接任务条件
	 * 4.接任务
	 * 	4.1 初始化任务
	 * 	4.2 初始化事件条件
	 *	4.3 接任务的同时有可能完成任务
	 * 5.通知客户端
	 * P.S 一个事件可能触发多个任务
	 */
	@Override
	public void onEvent(GameEventListener listener, GameEvent event) {
		Player player = event.getPlayer();
		// 取得全部开启的任务
		List<TaskCfg> cfgs = TaskCfgCache.me().getByOpen(true);
		
		// 取得全部接取的任务
		List<Task> tasks = player.getTasksFkPlayerId();
		
		Set<Integer> taskIds = Sets.newHashSet();
		Map<Integer,Integer> finishTasks = player.getPlayerDatasFkPlayerId().getPlayerDataProxy().getFinishTasks();
		taskIds.addAll(finishTasks.keySet());
		for (Task task : tasks) {
			taskIds.add(task.getCid());
		}
		
		List<TaskInfo> addTasks = Lists.newArrayList();

		for (TaskCfg taskCfg : cfgs) {
			// 任务已存在
			if (taskIds.contains(taskCfg.getId())) {
				continue;
			}
			
			int conditionId = taskCfg.getAcceptCondId();
			// 取得事件条件
			EventConditionCfg eventConditionCfg = EventConditionCfgCache.me().getById(conditionId);
			if (eventConditionCfg==null) {
				return;
			}
			
			// 检查与事件源是否匹配
			int eventId = eventConditionCfg.getEventId();
			if(event.getEventType() != eventId){
				continue;
			}

			//接任务：用的是接任务的条件参数
			Map params = taskCfg.getAcceptParams();
			boolean trigger = (params == null || params.isEmpty());
			
			Task task = null;
			if (trigger) {
				task = TaskManager.me().acceptTask(player, taskCfg);
			}else {
				event.push(new GameEventStack(eventId,conditionId, params, 0,0, trigger));
				listener.onEvent(event);
				GameEventStack eventStack = event.peek();
				// 条件触发成功
				if(eventStack.isTrigger()){
					task = TaskManager.me().acceptTask(player, taskCfg);
				}
			}
			
			
			if (task!=null) {
				addTasks.add(TaskMsgBuilder.createTaskInfo(player, ChangeType.ADD, task));
			}
		}
		// 加载玩家触发不推送
		if(event.getIn().containsKey(EventConditionKey.LOAD_PLAYER)){
			return;
		}
		TaskManager.me().notifyTaskInfos(player, addTasks);
	}
}
